package fr.unice.outils;

import java.io.IOException;
import java.net.URL;
import java.util.List; 
import java.util.Scanner; 

import com.google.gdata.client.Query;
import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.Category;
import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YouTubeNamespace;
import com.google.gdata.util.ServiceException;

public class Results_videos{

        /**
         * The name of the server hosting the YouTube GDATA feeds
         */
        public static final String YOUTUBE_GDATA_SERVER = "http://gdata.youtube.com";

        /**
         * The URL of the "Videos" feed
         */
        public static final String VIDEOS_FEED = YOUTUBE_GDATA_SERVER
                        + "/feeds/api/videos";

        /**
         * The URL of the "Standard" feed
         */
        public static final String STANDARD_FEED = YOUTUBE_GDATA_SERVER
                        + "/feeds/api/standardfeeds/";

        /**
         * Prints a VideoEntry, optionally showing its responses and comment feeds.
         *
         * @param prefix
         *            a string to be shown before each entry
         * @param videoEntry
         *            the VideoEntry to be printed
         * @param showCommentsAndResponses
         *            true if the comments and responses feeds should be printed
         * @throws ServiceException
         *             If the service is unable to handle the request.
         * @throws IOException
         *             error sending request or reading the feed.
         */
        private static String printVideoEntry(String prefix, VideoEntry videoEntry,
                        boolean showCommentsAndResponses) throws IOException, ServiceException {

                String results = null;

                YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
                if(mediaGroup != null) {

                        List<MediaThumbnail> liste = mediaGroup.getThumbnails();
                        //recupere le titre de la video
                        String titre = videoEntry.getTitle().getPlainText();

                        String nom=videoEntry.getHtmlLink().getHref();
                        Scanner scanner = new Scanner(nom);
                        scanner.useDelimiter("v=");
                        String adr = scanner.next();
                        String nomVideo = scanner.next();
                        titre=titre.replaceAll("[']", " ");
                        titre=titre.replaceAll("[\"]", " ");
                        results ="<span class=\"video\">";
                        //affiche la premiere miniature de la video 
                        results +="<br/><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\"><tr><td width=\"130px\"><a style='cursor:\'pointer\';' onclick='addPlayList(\""+ liste.get(0).getUrl()+"\",\""+nomVideo+"\",\""+titre+"\");'><img src=\"" + liste.get(0).getUrl()+"\"></a>";
                        results +="<span class=\"infovideo\">";


                        if (videoEntry.getTitle() != null) {
                        //String titre = videoEntry.getTitle().getPlainText();
                        int longeurTitreSouhaite = 24; 
                        results+="</td><td><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\"><tr>";
                        results += "<td colspan=\"2\"><span class=\"soustitre\" ><a target=\"_blank\" href=\""+videoEntry.getHtmlLink().getHref()+"\" title=\""+titre+"\">";
                        if(titre.length()> longeurTitreSouhaite){
                                String titreAbreg = titre.substring(0, longeurTitreSouhaite);
                                titreAbreg += "...";
                                 results+= titreAbreg;
                        }
                        else{
                                results += titre;
                        }
                        results+="</a></span></td></tr>";
                }

                        try{
                                //affiche le nombre de fois que la video a ete vue
                                results +="<tr><td width=\"20px\"><img src=\"images/oeil.png\" /></td><td>&nbsp;"  + videoEntry.getStatistics().getViewCount()+"</td></tr>";


                                //affiche la duree de la video
                                long dureeSec = mediaGroup.getDuration();
                                long dureeMin = dureeSec/60; 
                                long dureeSecRestante = dureeSec%60;
                                results+="<tr><td><img src=\"images/horloge.jpg\" /></td>";
                                results +="<td>&nbsp;" + dureeMin;
                                if(dureeSecRestante<=9)
                                        results +=":0"; 
                                else
                                        results +=":"; 
                                results+=dureeSecRestante+"</td></tr>";
                        }
                        catch(Exception e){
                        }

                        results +="<tr><td align=\"center\" colspan=\"2\"><img style=\"cursor:pointer;border:0;\" onclick='addPlayList(\""+ liste.get(0).getUrl()+"\",\""+nomVideo+"\",\""+titre+"\");' title=\"Ajouter &agrave; la playlist\" src=\"images/plus.png\" width=\"20px\"</td></tr></table>";
                        results +="</span>";//fin infovideo
                        results +="</td></tr></table></td></tr></span>";//fin video
                }
                /*
                if (videoEntry.getSummary() != null) {
                        results += "<br/> Summary: "+ videoEntry.getSummary().getPlainText();
                }*/

                /*
                if (showCommentsAndResponses) {
                        printResponsesFeed(videoEntry);
                        System.out.println("");
                        printCommentsFeed(videoEntry);
                        System.out.println("");
                        System.out.println("");
                }*/
                return results;
        }



        /**
         * Searches the VIDEOS_FEED for search terms and print each resulting
         * VideoEntry.
         *
         * @param service
         *            a YouTubeService object.
         * @throws ServiceException
         *             If the service is unable to handle the request.
         * @throws IOException
         *             error sending request or reading the feed.
         */
        public static String searchFeed(YouTubeService service, String searchTerms, String order, String category, String adultContent, String startIndex, String pageCour)
        throws IOException, ServiceException {
                YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));

                if(!category.equals("All")){
                        Query.CategoryFilter categoryFilter = new Query.CategoryFilter();
                        //this restricts to videos in the category of "category".
                        categoryFilter.addCategory(new Category(YouTubeNamespace.CATEGORY_SCHEME, category));
                        query.addCategoryFilter(categoryFilter);
                }

                //query.setTime(YouTubeQuery.Time.ALL_TIME);

                // order results by the number of views (most viewed first)
                //query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);
                if(order.equals("RELEVANCE")){
                        query.setOrderBy(YouTubeQuery.OrderBy.RELEVANCE);
                }
                if(order.equals("VIEW_COUNT")){
                        query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);
                }
                if(order.equals("UPDATED")){
                        query.setOrderBy(YouTubeQuery.OrderBy.PUBLISHED);
                }
                if(order.equals("RATING")){
                                query.setOrderBy(YouTubeQuery.OrderBy.RATING);
                }

                if(adultContent.equals("true")){
                        // do not exclude restricted content from the search results
                        // (by default, it is excluded)
                        query.setIncludeRacy(true);
                }
                else{
                        query.setIncludeRacy(false);
                }


                int videos_par_page = 20; //=max_result , restera une constante
                int nbr_total_de_videos=0;
                //int page_cour= Integer.parseInt(pageCour);
                int numero_page= Integer.parseInt(pageCour);

                int starIndex = Integer.parseInt(startIndex); //va devenir un parametre qd on clique sur les bouttons de navigation


                //boucle pour compter le nombre total de video trouvees
                for(int g=1;g<=100;g=g+20){
                        query.setStartIndex(g);
                        query.setMaxResults(videos_par_page);
                        query.setVideoQuery(searchTerms);
                        VideoFeed videoFeed2 = service.query(query, VideoFeed.class);
                        if(videoFeed2 == null){break;}
                        for (VideoEntry ve : videoFeed2.getEntries()) {
                                nbr_total_de_videos++;
                        }
                }

                String results = null;

                //afficher 20 videos sur une page
                        query.setStartIndex(starIndex);
                        query.setMaxResults(videos_par_page);//valeur max 50 possible
                        query.setVideoQuery(searchTerms);
                        VideoFeed videoFeed = service.query(query, VideoFeed.class);

                        //affiche une ligne d'information sur la requete soumise
                        //results +="<div id=\"blockvideos\">";
                        results = "&nbsp;<span class=\"titre\" >R&eacute;sultats";
                        results+=" de <b>"+starIndex+"</b> &agrave; <b>";
                        if(videos_par_page < nbr_total_de_videos)
                                results +=(starIndex+20);
                        
                        else
                                results +=nbr_total_de_videos;
                        
                        results+="</b> sur <b>"+nbr_total_de_videos+"</b><br/></span>";
                        
                        double rapport = (double)nbr_total_de_videos/videos_par_page;
		                Double dnbr_total_de_page = new Double(Math.ceil(rapport));
		                int nbr_total_de_page = (int)dnbr_total_de_page.intValue(); 
		                
                        if(nbr_total_de_page>1){
                            results +="<center><div class=\"texte_recherche\" id=\"navigation\">";
                            results +="&nbsp<a href=\"javascript:search('null', 1, 1);\"><img border='0' src='images/premier.png' title='Premier'/></a>";
                            if(numero_page>1){
                                    results +="&nbsp<a href=\"javascript:search('null', "+(starIndex-20)+", "+(numero_page-1)+");\"><img border='0' src='images/precedent.png' title='Pr&eacute;c&eacute;dent'/></a>";
                            }

                            results +="&nbsp;Page "+numero_page;
                            /* for(int i=0;i<nbr_total_de_page; i++){
                                    results +="&nbsp<a href=\"javascript:search('null', "+(((i+1)*20)-19)+", "+(i+1)+");\">"+(i+1)+"</a>";
                            }*/
                            if(numero_page<nbr_total_de_page){
                                    results +="&nbsp<a href=\"javascript:search('null', "+(starIndex+20)+", "+(numero_page+1)+");\"><img border='0' src='images/suivant.png' title='Suivant'/></a>";
                            }
                            results +="&nbsp<a href=\"javascript:search('null', "+((nbr_total_de_page*20)-19)+", "+nbr_total_de_page+");\"><img border='0' src='images/dernier.png' title='Dernier'/></a>";
                            
                            results +="</div></center>";
                        }
                        
                        
                        
						results+="<div class='caroussel' style='height:375px;' >";
						results+="<div id='boite_englobante_1' style='height:375px;width:253px'>";
						results+="<div id='fleche_haut' align='center'> <img src='images/arrow-up.gif' id='arrow_up_image' onmouseout='StopperDefilement(this);' onmouseover='LancerDefilement(this,1); '/> </div>";
						results+="<div class='boite_fenetre' style='height:305px;'>";
						results+="<div id='div_miniatures_1' style='position: relative;' >";

		           /*     if(nbr_total_de_page>1){
	                        results +="<center><div id=\"navigation\"><h3>";
	                        results +="Page "+numero_page+"<br/>";
	                        if(numero_page>1){
	                                results +="&nbsp<a href=\"javascript:search('null', "+(starIndex-20)+", "+(numero_page-1)+");\">Précédent</a>";
	                        }
	                        for(int i=0;i<nbr_total_de_page; i++){
	                                results +="&nbsp<a href=\"javascript:search('null', "+(((i+1)*20)-19)+", "+(i+1)+");\">"+(i+1)+"</a>";
	                        }
	                        if(numero_page<nbr_total_de_page){
	                                results +="&nbsp<a href=\"javascript:search('null', "+(starIndex+20)+", "+(numero_page+1)+");\">Suivant</a>";
	                        }
	                        results +="</h3></div></center>";
	                }*/
                        for (VideoEntry ve : videoFeed.getEntries()) {

                                results += printVideoEntry("", ve, false);

                        } 




                results+="</div>";
				results+="</div>";
				results+="<div id='fleche_bas' align='center'><img src='images/arrow-down.gif' id='arrow_down_image' onmouseout='StopperDefilement(this);' onmouseover='LancerDefilement(this,1);' /></div>";
				results+="</div>";
				results+="</div>";
                return results;
        }

        public static String searchStandardFeed(YouTubeService service, String standardFeed, String startIndex, String pageCour)
        throws IOException, ServiceException {
                String feedUrl = STANDARD_FEED+standardFeed;
                YouTubeQuery query = new YouTubeQuery(new URL(feedUrl));

                int videos_par_page = 20; //=max_result , restera une constante
                int nbr_total_de_videos=0;
                //int page_cour= Integer.parseInt(pageCour);
                int numero_page= Integer.parseInt(pageCour);

                int starIndex = Integer.parseInt(startIndex); //va devenir un parametre qd on clique sur les bouttons de navigation


                //boucle pour compter le nombre total de video trouvees
                for(int g=1;g<=100;g=g+20){
                        query.setStartIndex(g);
                        query.setMaxResults(videos_par_page);
                        VideoFeed videoFeed2 = service.query(query, VideoFeed.class);
                        if(videoFeed2 == null){break;}
                        for (VideoEntry ve : videoFeed2.getEntries()) {
                                nbr_total_de_videos++;
                        }
                }

                String results = null;

                //afficher 20 videos sur une page
                        query.setStartIndex(starIndex);
                        query.setMaxResults(videos_par_page);//valeur max 50 possible
                        VideoFeed videoFeed = service.query(query, VideoFeed.class);

                        //affiche une ligne d'information sur la requete soumise
                        //results +="<div id=\"blockvideos\">";
//                      affiche une ligne d'information sur la requete soumise
                        if(standardFeed.equals("most_viewed")){
                        results = "&nbsp<span class=\"titre\" >Les vid&eacute;os les plus vues";
                        }
                        if(standardFeed.equals("top_rated")){
                                results = "&nbsp<span class=\"titre\" >Les mieux not&eacute;es";
                        }
                        if(standardFeed.equals("most_discussed")){
                                results = "&nbsp<span class=\"titre\" >Les plus discut&eacute;es";
                        }
                        if(standardFeed.equals("top_favorites")){
                                results = "&nbsp<span class=\"titre\" >Les favorites";
                        }
                        if(standardFeed.equals("most_responded")){
                                results = "&nbsp<span class=\"titre\" >Les plus comment&eacute;es";
                        }
                        if(standardFeed.equals("most_recent")){
                                results = "&nbsp<span class=\"titre\" >Les plus r&eacute;centes</span>";
                        }

                        if(videos_par_page < nbr_total_de_videos){
                                results +="&nbsp de <b>"+starIndex+"</b>- <b>"+(starIndex+20)+"</b> sur <b>"+nbr_total_de_videos+"</b><br/></span>";
                        }
                        else{
                                results +="&nbsp de <b>"+starIndex+"</b>- <b>"+nbr_total_de_videos+"</b> sur <b>"+nbr_total_de_videos+"</b><br/></span>";
                        }

                        double rapport = (double)nbr_total_de_videos/videos_par_page;
                Double dnbr_total_de_page = new Double(Math.ceil(rapport));
                int nbr_total_de_page = (int)dnbr_total_de_page.intValue(); 


                        if(nbr_total_de_page>1){
                                results +="<center><div class=\"texte_recherche\" id=\"navigation\">";
                                results +="&nbsp<a href=\"javascript:search('null', 1, 1);\"><img border='0' src='images/premier.png' title='Premier'/></a>";
                                if(numero_page>1){
                                        results +="&nbsp<a href=\"javascript:search('"+standardFeed+"', "+(starIndex-20)+", "+(numero_page-1)+");\"><img border='0' src='images/precedent.png' title='Pr&eacute;c&eacute;dent'/></a>";
                                }

                                results +="&nbsp;Page "+numero_page;
                                /* for(int i=0;i<nbr_total_de_page; i++){
                                        results +="&nbsp<a href=\"javascript:search('null', "+(((i+1)*20)-19)+", "+(i+1)+");\">"+(i+1)+"</a>";
                                }*/
                                if(numero_page<nbr_total_de_page){
                                        results +="&nbsp<a href=\"javascript:search('"+standardFeed+"', "+(starIndex+20)+", "+(numero_page+1)+");\"><img border='0' src='images/suivant.png' title='Suivant'/></a>";
                                }
                                results +="&nbsp<a href=\"javascript:search('"+standardFeed+"', "+((nbr_total_de_page*20)-19)+", "+nbr_total_de_page+");\"><img border='0' src='images/dernier.png' title='Dernier'/></a>";
                                
                                results +="</div></center>";
                                
                        }
                        results+="<div class='caroussel' style='height:375px;' >";
						results+="<div id='boite_englobante_1' style='height:375px;width:253px'>";
						results+="<div id='fleche_haut' align='center'> <img src='images/arrow-up.gif' id='arrow_up_image' onmouseout='StopperDefilement(this);' onmouseover='LancerDefilement(this,1); '/> </div>";
						results+="<div class='boite_fenetre' style='height:305px;'>";
						results+="<div id='div_miniatures_1' style='position: relative;' >";
						
                        for (VideoEntry ve : videoFeed.getEntries()) {
                                results += printVideoEntry("", ve, false);
                        }
                        
                        results+="</div>";
        				results+="</div>";
        				results+="<div id='fleche_bas' align='center'><img src='images/arrow-down.gif' id='arrow_down_image' onmouseout='StopperDefilement(this);' onmouseover='LancerDefilement(this,1);' /></div>";
        				results+="</div>";
        				results+="</div>";


                /*if(nbr_total_de_page>1){
                        results +="<center><div id=\"navigation\"><h3>";
                        results +="Page "+numero_page+"<br/>";
                        if(numero_page>1){
                                results +="&nbsp<a href=\"javascript:search('"+standardFeed+"', "+(starIndex-20)+", "+(numero_page-1)+");\">Précédent</a>";
                        }
                        for(int i=0;i<nbr_total_de_page; i++){
                                results +="&nbsp<a href=\"javascript:search('"+standardFeed+"', "+(((i+1)*20)-19)+", "+(i+1)+");\">"+(i+1)+"</a>";
                        }
                        if(numero_page<nbr_total_de_page){
                                results +="&nbsp<a href=\"javascript:search('"+standardFeed+"', "+(starIndex+20)+", "+(numero_page+1)+");\">Suivant</a>";
                        }
                        results +="</h3></div></center>";
                }*/
                return results;
        }
}
